package jdbc;

import java.sql.*;

public class TMySql {
    private static final String URL = "jdbc:mysql://10.10.61.14:8080/jdbc";
    private static final String USER = "jdbc";
    private static final String PASSWORD = "jdbc123!";

    public static void main(String[] args) {
        // 使用try-with-resources自动关闭资源
        try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("SELECT * FROM t_update")) {

            System.out.println("数据库连接成功！");
            printResultSet(resultSet);

        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void printResultSet(ResultSet resultSet) throws SQLException {
        // 获取结果集的元数据
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();

        // 打印表头
        for (int i = 1; i <= columnCount; i++) {
            System.out.printf("%-20s", metaData.getColumnName(i));
        }
        System.out.println();

        // 打印分隔线
        for (int i = 1; i <= columnCount; i++) {
            System.out.print("--------------------");
        }
        System.out.println();

        // 打印数据
        while (resultSet.next()) {
            for (int i = 1; i <= columnCount; i++) {
                String value = resultSet.getString(i);
                System.out.printf("%-20s", value != null ? value : "NULL");
            }
            System.out.println();
        }
    }
}
